package com.bluefuture.common.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.bluefuture.common.exception.GlobalException;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: leo
 * @date: 2019/9/9
 */
public class OSSUtil {

//    private static String endpoint = "oss-cn-shenzhen.aliyuncs.com";
    private static String endpoint = "oss-cn-beijing.aliyuncs.com";

    private static String accessKeyId = "LTAI5tN6endtPHYABXtCsQCq";

    private static String accessKeySecret = "3PsHMQtglCD1rYH4UH0S2siPEfH8cf";

    private static String bucketName = "bluefuture";

    private static OSSClient ossClientStatic;

    static {
        ossClientStatic = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 上传到OSS服务器 如果同名文件会覆盖服务器上的
     *
     * @param fileName 文件名称 包括后缀名
     * @param instream 文件流
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public static String upload(String fileName, InputStream instream) {
        String resultStr = "";
        try {
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 上传文件 (上传文件流的形式)
            PutObjectResult putResult = ossClientStatic.putObject(bucketName, fileName, instream, objectMetadata);
            // 解析结果
            resultStr = putResult.getETag();
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(ResultEnum.IMG_UPLOAD_ERROR);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultStr;
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public static String getUrl(String key, String option) {
        if (StringUtils.isBlank(key)) {
            return "";
        }
        return "http://" + bucketName + "." + endpoint + "/" + key + option;
    }

}
